<template>
    <div class="job-list">
        <div class="job-list-header">
            <h2 class="job-list-title">任务列表</h2>
        </div>
        
        <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
            <van-empty v-if="jobList.length === 0" description="暂无任务" />
            
            <van-cell-group inset v-for="(job, index) in jobList" :key="index" class="job-item">
                <van-cell title="任务函数" :value="getFunctionName(job.name)" />
                <van-cell title="Cron表达式" :value="job.cron_expression" />
                <van-cell title="创建时间" :value="job.created_at" />
                <van-cell title="下次执行时间" :value="getNextExecutionTime(job.cron_expression)" />
                <van-cell title="延迟类型" :value="getTime_type(job.time_type)" />
                <template v-if="job.time_type === 'jitter_time'">
                    <van-cell title="延迟时间" :value="job.jitter_time" />
                </template>
                <template v-if="job.time_type === 'delay_time'">
                    <van-cell title="固定时间" :value="job.delay_time" />
                </template>

                <van-cell title="执行状态">
                    <template #value>
                        <van-tag :type="getStatusType(job.is_active)">{{ getStatusText(job.is_active) }}</van-tag>
                    </template>
                </van-cell>
                <van-cell>
                    <template #value>
                        <div class="job-actions">
                            <van-button size="small" type="primary" @click="toggleJobStatus(job)" plain>
                                {{ job.is_active ? '暂停' : '启动' }}
                            </van-button>
                            <van-button size="small" type="danger" @click="confirmDelete(job)" plain>
                                删除
                            </van-button>
                        </div>
                    </template>
                </van-cell>
            </van-cell-group>
            
            <!-- 分页组件 -->
            <div class="pagination-container" v-if="jobList.length > 0">
                <Pagination
                    :current-page="currentPage"
                    :total-pages="totalPages"
                    :total="totalItems"
                    @page-change="handlePageChange"
                />
            </div>
        </van-pull-refresh>

        <!-- 删除确认对话框 -->
        <van-dialog
            v-model:show="showDeleteConfirm"
            title="确认删除"
            show-cancel-button
            @confirm="deleteJob"
        >
            <div class="dialog-content">
                确定要删除该任务吗？此操作不可恢复。
            </div>
        </van-dialog>
    </div>
</template>

<script setup>
import { ref, onMounted, computed, defineEmits, defineExpose } from 'vue';
import { 
    PullRefresh as VanPullRefresh,
    Cell as VanCell,
    CellGroup as VanCellGroup,
    Button as VanButton,
    Tag as VanTag,
    Dialog as VanDialog,
    Empty as VanEmpty,
    showToast
} from 'vant';
import Pagination from '@/Pages/compontents/Pagination.vue';
import apiUrls from '@/config/apiUrls';
import request from '@/utils/request';
import { getNextExecutionTime } from '@/utils/utils';
// 任务列表数据
const jobList = ref([]);
const refreshing = ref(false);
const showDeleteConfirm = ref(false);
const jobToDelete = ref(null);

// 分页相关
const currentPage = ref(1);
const pageSize = ref(5);
const totalItems = ref(0);
const totalPages = computed(() => Math.ceil(totalItems.value / pageSize.value));



// 处理页码变化
const handlePageChange = (page) => {
    currentPage.value = page;
    fetchJobList();
};

// 获取任务列表
const fetchJobList = async () => {
    try {
        const response = await request.get(apiUrls.schedule.tasks, {
            params: {
                page: currentPage.value,
                per_page: pageSize.value
            }
        });
        
        if (response.code === 200 && response.data) {
            jobList.value = response.data.data || [];
            totalItems.value = response.data.total || 0;
            
            // 如果后端返回的当前页与前端不一致，更新前端页码
            if (response.data.current_page) {
                currentPage.value = response.data.current_page;
            }
            
            console.log('任务列表数据:', response.data);
        } else {
            showToast(response.message || '获取任务列表失败');
        }
    } catch (error) {
        console.error('获取任务列表失败:', error);
        showToast('获取任务列表失败');
    }
};

// 下拉刷新
const onRefresh = async () => {
    refreshing.value = true;
    currentPage.value = 1; // 重置为第一页
    try {
        await fetchJobList();
    } finally {
        refreshing.value = false;
    }
};


// 延迟类型
const getTime_type = (functionKey)=>{
    const functionMap = {
        'cron_expression': '不延时',
        'delay_time': '固定延迟时间',
        'jitter_time': '间隔时间'
    };
    return functionMap[functionKey] || functionKey;
}

// 获取函数名称
const getFunctionName = (functionKey) => {
    const functionMap = {
        'dawn_job': '定时打卡',
        'log_job': '定时日志'
    };
    return functionMap[functionKey] || functionKey;
};

// 获取状态样式
const getStatusType = (status) => {
    const statusMap = {
        'true': 'success',
        // '1': 'warning',
        'false': 'danger',
        // 'false': 'primary'
    };
    return statusMap[status] || 'default';
};

// 获取状态文本
const getStatusText = (status) => {
    const statusMap = {
       'true': '运行中',
        'false': '已暂停',
        // 'failed': '失败',
        // 'pending': '等待中'
    };
    return statusMap[status] || status;
};

// 切换任务状态
const toggleJobStatus = async (job) => {
    try {
        console.log('任务状态: ');
        console.log(job.is_active);
        const action = job.is_active;
        const response = await request.patch(`${apiUrls.schedule.tasks}/${job.id}/toggle-status`, {
            data: {
                action: !action
            }
        });
        
        if (response.code === 200) {
            showToast(response.message || `任务${action === 'pause' ? '暂停' : '启动'}成功`);
            await fetchJobList(); // 刷新列表
        } else {
            showToast(response.message || '操作失败');
        }
    } catch (error) {
        console.error('操作失败:', error);
        showToast('操作失败');
    }
};

// 确认删除
const confirmDelete = (job) => {
    jobToDelete.value = job;
    showDeleteConfirm.value = true;
};

// 删除任务
const deleteJob = async () => {
    if (!jobToDelete.value) return;
    
    try {
        const response = await request.delete(`${apiUrls.schedule.tasks}/${jobToDelete.value.id}`);
        
        if (response.code === 200) {
            showToast(response.message || '删除成功');
            await fetchJobList(); // 刷新列表
        } else {
            showToast(response.message || '删除失败');
        }
    } catch (error) {
        console.error('删除失败:', error);
        showToast('删除失败');
    } finally {
        jobToDelete.value = null;
    }
};


// 组件挂载时加载任务列表
onMounted(() => {
    fetchJobList();
});

defineExpose({ fetchJobList });
</script>

<style scoped>
.job-list {
    padding: 12px;
    background-color: #ffffff;
    max-width: 100%;
    box-sizing: border-box;
}

.job-list-header {
    margin-bottom: 16px;
    padding: 0 4px;
}

.job-list-title {
    font-size: 18px;
    font-weight: 600;
    color: #1989fa;
    margin: 0;
    line-height: 1.4;
}

.job-item {
    margin-bottom: 12px;
    border-radius: 8px;
    overflow: hidden;
    background-color: #fff;
    box-shadow: 0 2px 10px rgba(0, 137, 250, 0.1);
    border: 1px solid rgba(25, 137, 250, 0.15);
}

:deep(.van-cell-group--inset) {
    margin: 0 0 12px;
    border-radius: 8px;
    overflow: hidden;
}

:deep(.van-cell) {
    padding: 12px 16px;
    background-color: #fff;
}

:deep(.van-cell::after) {
    border-bottom: 1px solid rgba(25, 137, 250, 0.12);
    left: 16px;
    right: 16px;
}

:deep(.van-cell:last-child::after) {
    display: none;
}

:deep(.van-cell__title) {
    flex: 2;
    color: #323233;
    font-weight: 500;
}

:deep(.van-cell__value) {
    flex: 3;
    color: #666;
    word-break: break-all;
    text-align: right;
}

.job-actions {
    display: flex;
    justify-content: flex-end;
    gap: 8px;
}

:deep(.van-tag) {
    padding: 2px 6px;
    font-size: 12px;
    border: 1px solid transparent;
}

:deep(.van-tag--success) {
    background-color: rgba(7, 193, 96, 0.1);
    color: #07c160;
    border-color: rgba(7, 193, 96, 0.3);
}

:deep(.van-tag--warning) {
    background-color: rgba(255, 170, 0, 0.1);
    color: #ff976a;
    border-color: rgba(255, 170, 0, 0.3);
}

:deep(.van-tag--danger) {
    background-color: rgba(238, 10, 36, 0.1);
    color: #ee0a24;
    border-color: rgba(238, 10, 36, 0.3);
}

:deep(.van-tag--primary) {
    background-color: rgba(25, 137, 250, 0.1);
    color: #1989fa;
    border-color: rgba(25, 137, 250, 0.3);
}

:deep(.van-button--small) {
    min-width: 64px;
    height: 32px;
    font-size: 12px;
    border-width: 1px;
}

:deep(.van-button--plain) {
    background-color: transparent;
    border-width: 1px;
}

:deep(.van-pull-refresh) {
    background-color: #ffffff;
}

:deep(.van-empty) {
    padding: 32px 0;
    background-color: #ffffff;
}

.dialog-content {
    padding: 20px 16px;
    text-align: center;
    color: #646566;
}

.pagination-container {
    padding: 16px 0;
    display: flex;
    justify-content: center;
}

/* 移动端适配 */
@media screen and (max-width: 480px) {
    .job-list {
        padding: 8px;
    }
    
    .job-list-header {
        margin-bottom: 12px;
    }
    
    .job-list-title {
        font-size: 16px;
    }
    
    :deep(.van-cell) {
        padding: 10px 12px;
    }
    
    :deep(.van-cell::after) {
        left: 12px;
        right: 12px;
    }
    
    :deep(.van-cell__title) {
        flex: 1;
        font-size: 13px;
    }
    
    :deep(.van-cell__value) {
        flex: 2;
        font-size: 13px;
    }
    
    :deep(.van-button--small) {
        min-width: 56px;
        height: 28px;
        font-size: 12px;
    }
}
</style>